package cn.stronglink.esm27.collection.iot.devices.esm27.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.ESM27MessageTools;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.ESM27ResponseMessageEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.SensorMeasuredDataEntity;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

public class GetAllSensorDataReturnHandle implements IMessageHandle<ESM27ResponseMessageEntity, Object> {
	private final static int SENSOR_COUNT=7;	// 传感器的数量
	private final static String ACTION_CODE="GetAllSensorDataReturn";
	private final static String TOPIC_NAME="ESM27ToService";		// MQ发送主题
	private final static Logger logger = LogManager.getLogger(GetAllSensorDataReturnHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	
	@Override
	public boolean isHandle(ESM27ResponseMessageEntity t) {
		if(t.getCommandCode()==0x0A) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ESM27ResponseMessageEntity t) {
		int offset=0;
		SensorMeasuredDataEntity entity = new SensorMeasuredDataEntity();
		entity.setDeviceAddress(t.getDeviceAddress());
		
		// 获取传感器的值
		float[] sersorValues=new float[SENSOR_COUNT];
		for(int i=0;i<SENSOR_COUNT;i++) {
			offset=i*4;
			sersorValues[i]=ByteUtil.bytesToFloat(t.getDatas(), offset);
		}
		entity.setSensorValues(sersorValues);
		
		// 获取经度
		offset+=4;
		entity.setLongitude(ByteUtil.bytesToFloat(t.getDatas(),offset));
		// 获取纬度
		offset+=4;
		entity.setLatitude(ByteUtil.bytesToFloat(t.getDatas(),offset));
		// 获取电池电压
		offset+=4;
		entity.setBatteryVoltage(ByteUtil.bytesToFloat(t.getDatas(),offset));
		// 传感器3的TWA报警
		offset+=4;
		entity.setAlarms(ESM27MessageTools.getAlarmInfoList(ByteUtil.byteArrayToInt(t.getDatas(),offset), false));
		// 泵状态
		offset+=1;
		entity.setPumpState(t.getDatas()[offset]);
		
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(ACTION_CODE);
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(entity);
		message.setIsSuccess(true);
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME, json);
		logger.info("发送[{}]到MQ完成:{}","获取所有传感器数据的反馈信息",json);
		return null;
	}

}
